#include "head.h"

void clean_stdin()
{
    int c;
    while ((c = getchar()) != '\n' && c != EOF)
        ;
}

void user_login(int sockfd, char *user_name)
{
    char buf[512];
    cmd_t Cmd;
    while (1)
    {
        int flag;
        bzero(&Cmd, sizeof(cmd_t));
        printf("Please enter 1 to sign up or enter 2 to log in\n");
        scanf(" %d", &flag);
        // printf("flag = %d\n",flag);
        switch (flag)
        {
        case 1:
            Cmd.token = CMD_SIGNUP;
            printf("用户注册：\n");
            break;
        case 2:
            Cmd.token = CMD_LOGIN;
            printf("用户登录：\n");
            break;
        default:
            clean_stdin();
            continue;
        }
        // printf("flag = %d\n",flag);
        // printf("Cmd.token = %d\n",Cmd.token);
        clean_stdin();
        printf("请输入用户名:\n");
        bzero(buf, sizeof(buf));
        read(STDIN_FILENO, buf, sizeof(buf));
        strcpy(Cmd.object, buf);
        strncpy(user_name, buf, strlen(buf) - 1);
        printf("请输入密码:\n");
        bzero(buf, sizeof(buf));
        read(STDIN_FILENO, buf, sizeof(buf));
        strcat(Cmd.object, buf);
        send(sockfd, &Cmd, sizeof(cmd_t), 0);
        // printf("Cmd.token = %d\n",Cmd.token);
        char state;
        recv(sockfd, &state, sizeof(char), 0);
        // printf("flag = %d\n",flag);
        // printf("Cmd.token = %d\n",Cmd.token);
        if (flag == 2)
        {
            if (state == '0')
            {
                printf("用户名不存在！\n");
            }
            else if (state == '1')
            {
                printf("用户名或密码不正确！\n");
            }
            else if (state == '2')
            {
                printf("登录成功！\n");
                return;
            }
        }
        else if (flag == 1)
        {
            if (state == '1')
            {
                printf("注册成功！\n");
                continue;
            }
            else if (state == '0')
            {
                printf("用户名已存在，注册失败！\n");
            }
        }
    }
}